<?php
//服务
namespace App\Http\Controllers\Web;

//引用
use App\Http\Controllers\Controller;
use App\Models\News;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class NewsController extends Controller
{
    public function index(Request $request) {
        $rules = [
            'catid'=>'integer|exists:news_type,id',
            'title'=>'string'
        ];
        $message = [
            'catid.*'=>'请选择正确的分类',
            'title.*'=>'请输入标题'
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(201,$validator->errors()->first());
        }
        try{
            $perPage = 5;
            if (isset($request->catid)){
                $res = News::where('status',1)->where('catid',$request->catid);
            }else{
                $res = News::where('status',1);
            }
            if (isset($request->title)){
                $res= $res->where('title','like','%'.$request->title.'%');
            }
            $res = $res->orderBy('listorder','desc')->paginate($perPage);//,['id','catid','title','small_title','image','read_count','created_at']);
            if ($res->isEmpty()){
                return show(202,'暂无活动信息');
            }
        }catch (\Exception $e){
            return show(202,'暂无活动信息');
        }
        return show(200,'活动信息',$res);

    }

    /**
     * 获取详情接口
     */
    public function read(Request $request) {
        $rules = [
            'id'=>'required|integer|exists:news,id',
        ];
        $message = [
            'id.*'=>'请选择正确的活动编号',
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(201,$validator->errors()->first());
        }
        $news = News::where('status',1)->find($request->id);

        if (!$news){
            return show(202,'不存在该活动');
        }


        try {
            DB::table('news')->increment('read_count');
        }catch(\Exception $e) {
            return show(200,'活动详情',$news);
        }
        return show(200,'活动详情',$news);
    }
}
